package com.zy.baselib.widget

import android.content.Context
import android.graphics.*
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.zy.baselib.R

/**
 * @author: shalei
 * @since: 2020-01-16 08:29
 * @Desc:
 **/
class CodeView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    View(context, attrs, defStyleAttr) {

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context) : this(context, null)

    private var mTextList = arrayListOf<String>()
    private var lastCode: String = ""
    private val mPointList = arrayListOf<Float>()

    private val mPaint = Paint()

    init {
        var mBgResId: Int = R.mipmap.bg_code
        var color: Int = ContextCompat.getColor(getContext(), R.color.blue)
        var size: Float = getContext().resources.getDimension(R.dimen.sp_13)
        if (attrs != null) {
            val ta = context.obtainStyledAttributes(attrs, R.styleable.CodeView)
            mBgResId = ta.getResourceId(R.styleable.CodeView_m_code_background, mBgResId)
            color = ta.getColor(R.styleable.CodeView_m_code_text_color, color)
            size = ta.getDimension(R.styleable.CodeView_m_code_text_size, size)
            ta.recycle()
        }
        setBackgroundResource(mBgResId)
        mPaint.isAntiAlias = true
        mPaint.color = color
        mPaint.textSize = size
        mPaint.strokeWidth = 3f
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }

    public fun setCode(code: String?) {
        if (!TextUtils.isEmpty(code)) {
            code?.let {
                val split = code.split("")
                mTextList.clear()
                mTextList.addAll(split)
            }
        }
        invalidate()
    }

    /**
     * 软键盘弹出，可能会导致ui重新绘制，onDraw多次被调用
     * 记住上一次的坐标，如果验证码没有发生变化，绘制在相同的地方
     */
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            if (mTextList.isNotEmpty()) {
                if(lastCode != getCode()) {
                    mPointList.clear()
                }
                var start: Float = 3f
                for ((i, s) in mTextList.withIndex()) {
                    if(lastCode != getCode()) {
                        mPointList.add(CheckUtil.getPositon(height))
                    }
                    canvas.drawText(s, start, mPointList[i], mPaint)
                    start += width / mTextList.size + 5 //5个像素的偏移量
                }
                lastCode = getCode()
            }
        }
    }

    public fun getCode(): String {
        if (mTextList.isEmpty()) return ""
        val sb = StringBuilder()
        for (s: String in mTextList) {
            sb.append(s)
        }
        return sb.toString()
    }

}